import React from "react";
import {inject, observer} from "mobx-react";
import {Bubble, Checkbox, DatePicker, Icon, List, Modal, Popover, Tools, Button} from "weaver-mobile";
import {Route, withRouter} from "react-router-dom";
import {WrAccordion, WrAlertPage, WrCardList, WrMenu, WrRemark, WrShow} from "../../../public";
import {observable, toJS} from "mobx";
import {BrowserHrm, RouteLayout} from "weaver-mobile-page";
import DetailEdit from "./detailEdit";
import ScoreDetail from "./scoreDetail";
import {Empty} from "../../plan/coms";
import {openHrmCard} from "../../../util";
import ProgramItemDetail from "../programItem/detail";

const CheckboxItem = Checkbox.CheckboxItem;
const getLabel = Tools.getLabel;

const programStatus = {//方案状态
    "": {label: getLabel(15808, "未设置"), color: "#D81D19"},
    "0": {label: getLabel(220, "草稿"), color: "#ACA207"},
    "1": {label: getLabel(19134, "审批中"), color: "#868686"},
    "2": {label: getLabel(236, "退回"), color: "#B916E8"},
    "3": {label: getLabel(508866, "已通过"), color: "#49D732"},
    "4": {label: getLabel(15808, "未设置"), color: "#D81D19"},
    "13": {label: getLabel(384564, "已禁用"), color: "#C8C8C8"}
};
const alertMessage = {
    1: {msg: getLabel(508557, "暂未开启任何考核周期")},
    2: {msg: getLabel(508609, "您暂时无权限查看此数据")},
    3: {msg: getLabel(509520, "暂未设置相应考核方案！"), icon: "no-data"},
}

/**
 * 考核方案-详情
 * jiansong 2019/11/8
 */
@inject("programViewStore", "programItemStore")
@withRouter
@observer
export default class Detail extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            type: "org", //下属方案sub/组织机构org
            path: this.props.location.pathname
        }
        this.store = this.props.programViewStore;
    }

    render() {
        const {
            detail, form, ckRichTextStore, showStatus, orgStore, msg, remarkLayout,
            programDetailStore, programScoreStore, onFormChange, programDetail, updateScoreData,
            programStatus, browserHrm, auditidsData, addStatus, alertPageType, remarkStore, backProgram
            , scoreDataList, form: {accessScoreData}, setAccessScoreDate
        } = this.store;
        return [
            <div className="roll programView-detail">
                <WrAlertPage show={msg == "1" && alertPageType !== ""}
                             msg={alertPageType && alertMessage[alertPageType].msg}
                             icon={alertPageType && alertMessage[alertPageType].icon}/>
                <WrShow show={msg == "1" && alertPageType === ""}>
                    <WrShow show={form.programid != "" && !addStatus}>
                        <div className="programView-content-title">
                            <span className="programView-content-title-name">{detail.programname}</span>
                            <span className="programView-content-title-other">
                                <WrShow show={!addStatus && detail.programstatus == "1"}>
                                    <span className="programView-content-title-audit"
                                          dangerouslySetInnerHTML={{__html: getLabel(129864, "待审批人") + "：" + detail.waitAuditName}}/>
                                </WrShow>
                                <WrShow show={!(!addStatus && detail.programstatus == "1")}>
                                    <span/>
                                </WrShow>
                                <span className="programView-content-title-more">
                                    <Popover
                                        mask
                                        visible={false}
                                        overlay={[
                                            (<Popover.Item key="0" value="scan">
                                                {getLabel(32061, "操作日志")}
                                            </Popover.Item>),
                                        ]}
                                        onSelect={this.handlePopoverSelect}
                                    >
                                         <span>
                                             {backProgram&&<span className="workrelate-status" style={{background: "red"}}>{getLabel('518208', '考核组方案')}</span>}
                                             {this.getStatus(detail.programstatus)}
                                             <Icon type="right"/>
                                        </span>
                                    </Popover>
                                </span>
                             </span>
                        </div>
                    </WrShow>
                    <WrShow show={addStatus || form.programid == ""}>
                        <div className="programView-content-title">
                            <span className="programView-content-title-name" style={{"lineHeight": "1.5"}}>
                                {detail.titlename}
                            </span>
                            <span className="programView-content-title-other" style={{"lineHeight": "1.5"}}>
                                <WrShow show={detail.noprogram && detail.nomsg != ""}>
                                    <span className="programView-content-title-audit" style={{color: "#D9001C"}}>
                                        {detail.nomsg}
                                    </span>
                                </WrShow>
                            </span>
                        </div>
                    </WrShow>
                    <div className="programView-detail-content"
                         style={{"marginTop": ((form.programid != "" && !addStatus) ? "5px" : "0")}}>
                        <div className="programView-content-date">
                            <List.FormItem
                                label={getLabel(19548, "生效日期")}
                                line
                                content={(<DatePicker.DatePickerInput
                                    mode="date"
                                    value={form.startdate}
                                    required
                                    disabled={!showStatus}
                                    onChange={date => onFormChange({startdate: date})}
                                />)}
                            />
                        </div>
                        <WrAccordion title={getLabel(386205, "考核明细")}>
                            <WrCardList
                                title={""}
                                full
                                hiddenHeader={!showStatus}
                                dataMapList={[{
                                    fieldname: "cate",
                                    showname: getLabel(455, "分类"),
                                }, {
                                    fieldname: "accessitemidspan",
                                    showname: getLabel(18085, "指标类型"),
                                }, {
                                    fieldname: "description",
                                    showname: getLabel(508669, "指标描述"),
                                }, {
                                    fieldname: "rate",
                                    showname: getLabel(6071, "权重"),
                                }, {
                                    fieldname: "target",
                                    showname: getLabel(18087, "目标值"),
                                }]}
                                dataList={(form.assessDetailData instanceof Array) ? toJS(form.assessDetailData) : []}
                                showAdd={showStatus}
                                showDelete={showStatus}
                                showCheckBox={showStatus}
                                onRowClick={(val) => {
                                    showStatus && this.props.history.push({
                                        pathname: this.state.path + "/detail",
                                        state: val
                                    })
                                }}
                                showDropList={false}
                                onAdd={() => this.props.history.push(this.state.path + "/detail")}
                                onDelete={val => onFormChange({assessDetailData: val})}
                                emptyComponent={<Empty title={getLabel(83553, "暂无数据")}></Empty>}
                            />
                        </WrAccordion>
                        <WrAccordion title={getLabel(15752, "考核说明")}>
                            <WrRemark
                                remark={form.remark}
                                remarkStore={remarkStore}
                                remarkLayoutStore={remarkLayout}
                                iconClick={() => {
                                    this.setState({remarkInitText: form.remark})
                                    this.props.history.push(remarkLayout.path)
                                }}
                                editable={showStatus}
                                onTextChange={(e) => onFormChange({remark: e})}
                                onOk={() => this.props.history.go(-1)}
                                onCancel={() => {
                                    onFormChange({remark: this.state.remarkInitText})
                                    this.props.history.go(-1)
                                }}
                            />
                        </WrAccordion>
                        <WrAccordion title={getLabel(506162, "考核评分")}>
                            <WrCardList
                                title={""}
                                full
                                hiddenHeader={!showStatus}
                                dataMapList={[{
                                    fieldname: "showid",
                                    showname: getLabel(508672, "评分人"),
                                    method: (data) => <div>{
                                        accessScoreData && accessScoreData.length > 0 && accessScoreData.map((element, idx) => {
                                            if (data.showid != undefined && data.showid != "" && data.showid.indexOf("," + element.checkuserid + ",") > -1) {
                                                return <div className="programView-detail-scoreDetail-div"><span style={{color: "#4D7AD8"}}
                                                onClick={(e) => openHrmCard(element.checkuserid, e)}>{element.checkusername}</span>
                                                {"(" + element.rate + "%)"}{element.templateid && <span>-{element.templatename}</span>}
                                                </div>
                                            }
                                        })
                                    }</div>
                                }, {
                                    fieldname: "showattr",
                                    showname: getLabel(125351, '会签属性'),
                                    method: (data) => data.showattr == 0 ? getLabel(15558, '依次逐个处理') : getLabel(15557, '会签')
                                }]}
                                dataList={toJS(scoreDataList)}
                                showAdd={showStatus}
                                showDelete={showStatus}
                                showCheckBox={showStatus}
                                onAdd={() => this.props.history.push(this.state.path + "/scoreDetail")}
                                onDelete={val => {setAccessScoreDate(val,1)}}
                                onRowClick={(val) => {
                                    showStatus && this.props.history.push({
                                        pathname: this.state.path + "/scoreDetail",
                                        state: val
                                    })
                                }}
                                showDropList={false}
                                emptyComponent={<Empty title={getLabel(83553, "暂无数据")}></Empty>}
                            />
                        </WrAccordion>
                        <div className="programView-content-audit">
                            <div className={!showStatus ? "workrelate-am-list-no-arrow audit-hidden-label" : undefined}>
                                <BrowserHrm
                                    label={getLabel(508675, "考核审批")}
                                    store={browserHrm}
                                    hasAdvanceSerach
                                    isSingle={false}
                                    type={1}
                                    onChange={(val, valSpan, valArray) => onFormChange({
                                        auditids: val,
                                        auditnames: valSpan
                                    })}
                                    valueArray={auditidsData}
                                    viewAttr={showStatus ? 2 : 1}
                                />
                                <WrShow show={showStatus}>
                                    <div className="manager-manager">
                                        <Button onClick={()=>this.getManagerManager()} className="manager-button">{getLabel('508574', '上级的上级')}</Button>
                                    </div>
                                </WrShow>
                            </div>
                        </div>
                        <WrShow show={!addStatus && detail.otherProgram != undefined && detail.otherProgram.length > 0}>
                            <WrAccordion title={getLabel(508677, "其他考核方案")}>
                                <div className="programView-content-other">
                                    {detail.otherProgram && detail.otherProgram.map(item =>
                                        <span>
                                            <a key={item.id} onClick={() => {
                                                onFormChange({
                                                    "programid": item.id,
                                                    "groupid": item.groupid,
                                                });
                                                programDetail();
                                            }}>{item.programname + "(" + this.getProgramStatus(item.programstatus) + ")"}{item.groupid &&
                                            <span>({getLabel('518208', '考核组方案')})</span>}</a>
                                        </span>
                                    )}
                                </div>
                            </WrAccordion>
                        </WrShow>
                    </div>
                </WrShow>
            </div>,
            <WrMenu
                data={this.props.menu}
                onSelect={val => {
                    if (val.props.path == "/performance/programView") {
                        onFormChange({resourceid: "", programtype: "", programid: ""});
                        programDetail();
                    } else {
                        this.props.history.push(val.props.path)
                    }
                }}
                buttonData={this.buildOperateButton()}
            />,
            <Route
                key="programView-detailEdit"
                path={this.state.path + "/detail"}
                render={() => (
                    <RouteLayout>
                        <DetailEdit/>
                    </RouteLayout>
                )}
            />,
            <Route
                key="programView-score-edit"
                path={this.state.path + "/scoredetail"}
                render={() => (
                    <RouteLayout>
                        <ScoreDetail/>
                    </RouteLayout>
                )}
            />,
            <Route
                key="programItem-detail"
                path={this.state.path + "/template"}
                render={() => (
                    <RouteLayout>
                        <div className="wm-route-layout">
                            <ProgramItemDetail updateListData={updateScoreData}/>
                        </div>
                    </RouteLayout>
                )}
            />
        ]
    }

    getProgramStatus = (val) => {
        return programStatus[val].label;
    }

    //获取被考核人上级的上级
    getManagerManager = () => {
        const {onFormChange, detail: {managerid2, managername2}} = this.store;
        if (managerid2 == '' || managerid2 == '0') {
            Bubble.warning(getLabel(509116, '直接上级的上级不存在,请重新选择!'))
        } else {
            onFormChange({
                auditids: managerid2,
                auditnames: managername2
            })
        }
    }

    //处理
    handlePopoverSelect = () => {
        this.store.logCurrent = 1;
        this.store.showtype = "log";
    }

    //获取方案状态
    getStatus = (val) => {
        var status = programStatus[val];
        return status ?
            <span className="workrelate-status" style={{background: status.color}}>{status.label}</span> :
            <span/>
    }

    //获取操作菜单
    buildOperateButton = () => {
        const {showStatus, canAdd, handleAdd, addStatus, cancelAdd, detail: {canResetScore, canedit, candelete, canquoteindex, programstatus, canaudit}} = this.store
        let menu = [];
        if (!addStatus) {
            canedit && menu.push({content: getLabel(30986, "保存"), onClick: () => this.handleFormOperation("save"),});
            canedit && menu.push({content: getLabel(725, "提交"), onClick: () => this.handleFormOperation("submit"),});
        }
        if (canedit && "" != programstatus && "13" == programstatus && !addStatus) {
            menu.push({content: getLabel(26472, "启用"), onClick: () => this.handleFormOperation("start"),});
        } else if (canedit && "" != programstatus && "0" != programstatus && !addStatus) {
            menu.push({content: getLabel(18096, "禁用"), onClick: () => this.handleFormOperation("forbidden")});
        }
        canAdd && !addStatus && menu.push({content: getLabel(365, "新建"), onClick: handleAdd});
        canaudit && !addStatus && menu.push({
            content: getLabel(142, "批准"),
            onClick: () => this.handleProgramAudit("approve"),
        });
        canaudit && !addStatus && menu.push({
            content: getLabel(236, "退回"),
            onClick: () => this.handleProgramAudit("return"),
        });
        candelete && menu.push({content: getLabel(91, "删除"), onClick: () => this.doDelete("delete"),});
        if (!addStatus && canResetScore) {
            menu.push({content: getLabel('516940', '重置评分'), onClick: () => this.doResetScore("resetScore"),});
        }
        if(!addStatus&&showStatus){
            menu.push({content: getLabel('17858','模板列表') , onClick: () => {
                    this.props.programItemStore.canadd=showStatus
                    this.props.history.push(this.state.path + "/item")
                }});
        }
        canedit && !addStatus && menu.push({
            content: getLabel(508694, "引用方案"),
            onClick: () => this.handleQuotePage(true),
        });
        canquoteindex && !addStatus && menu.push({
            content: getLabel(508693, "引用指标"),
            onClick: () => this.handleQuotePage(false),
        });
        if (addStatus) {
            menu.push({content: getLabel(30986, "保存"), onClick: () => this.handleFormOperation("save")});
            menu.push({content: getLabel(725, "提交"), onClick: () => this.handleFormOperation("submit")});
            menu.push({content: getLabel('17858','模板列表') , onClick: () => {
                    this.props.programItemStore.canadd=showStatus
                    this.props.history.push(this.state.path + "/item")
                }});
            menu.push({content: getLabel(508694, "引用方案"), onClick: () => this.handleQuotePage(true)});
            menu.push({content: getLabel(513682, "取消新建"), onClick: cancelAdd});
        }
        return menu;
    }

    //跳转到引用方案或方案指标页面
    handleQuotePage = (isQuoteProgram) => {
        this.store.quoteProgram = isQuoteProgram;
        this.store.handleQuoteParamsChange({programtype: this.store.form.programtype});
        this.props.history.push(this.state.path + "/quote")
    }

    //删除
    doDelete(type) {
        const {handleProgram} = this.store;
        Modal.alert(getLabel(386786, "信息确认"), getLabel(512710, "确定删除此考核方案？"), [
            {text: getLabel(31129, "取消")},
            {text: getLabel(826, "确定"), onPress: () => handleProgram(type, this.props.updateListData)}
        ])
    }

    //重新评分
    doResetScore(type) {
        const {handleProgram} = this.store;
        Modal.alert(getLabel(386786, "信息确认"), getLabel('516953', '重置评分会影响进行中的评分数据，确定要重置？'), [
            {text: getLabel(31129, "取消")},
            {text: getLabel(826, "确定"), onPress: () => handleProgram(type)}
        ])
    }

    //方案审核操作
    handleProgramAudit(operation) {
        let {form: {programid}, programAuditOperation} = this.store;
        let title = operation == "approve" ? getLabel(508727, "确定批准此考核方案？") : getLabel(508728, "确定退回此考核方案？");
        let params = {
            programid: programid,
            operation: operation,
        };
        Modal.alert(getLabel(386786, "信息确认"), title, [
            {text: getLabel(31129, "取消")},
            {text: getLabel(826, "确定"), onPress: () => programAuditOperation(params, this.props.updateListData)}
        ])
    }

    //校验表单
    handleFormOperation = (type) => {
        const {handleProgram, programDetailStore, programScoreStore, form: {startdate, assessDetailData, accessScoreData}, detail: {accessItemList}} = this.store;
        //校验方案生效日期
        if (startdate == undefined || startdate == "") {
            Bubble.warning(getLabel(509122, "请选择生效日期！")); // 错误提示
            return false;
        }

        let flag = accessScoreData.every(item => item.templateid);
        if (!flag && assessDetailData.length == 0) {
            Bubble.warning(getLabel('517028', '请添加考核指标或给每个评分人设置考核模板'));
            return false;
        }
        if (assessDetailData.length > 0) {
            //校验考核明细权重
            let rateSum = 0, dataFlag = false;
            assessDetailData.map(item => {
                rateSum += Number(item.rate);
            });
            if (rateSum.toFixed(2) != 100) {
                Bubble.warning(getLabel(509125, "考核项权重设置不正确,权重总和需等于100！"));
                return false;
            }

            //校验相同类型指标描述
            assessDetailData.map(i => {
                assessDetailData.map(j => {
                    if (i.id != j.id && i.accessitemid == j.accessitemid && i.description == j.description) {
                        dataFlag = true;
                    }
                })
            })

            if (dataFlag) {
                Bubble.warning(getLabel(509126, "相同指标类型的指标描述不能相同！"));
                return false;
            }
        }

        let scoreSum = 0;
        accessScoreData.map(item => scoreSum += Number(item.rate));
        if (scoreSum.toFixed(2) != 100) {
            Bubble.warning(getLabel(509120, "评分人权重设置不正确, 权重总和需等于100！"));
            return false;
        }
        const operateTypeTitle = {
            "save": getLabel(509127, "确定保存此考核方案？"),
            "submit": getLabel(509128, "确定提交此考核方案？"),
            "start": getLabel(509130, "确定启用此考核方案？"),
            "forbidden": getLabel(509131, "确定禁用此考核方案？"),
        }
        Modal.alert(getLabel(386786, "信息确认"), operateTypeTitle[type], [
            {text: getLabel(31129, "取消")},
            {text: getLabel(826, "确定"), onPress: () => handleProgram(type, this.props.updateListData)}
        ])
    }

}